<template>
  <div>
    <v-chart :forceFit="true" :height="height" :data="data" :padding="paddingCopy">
      <v-tooltip />
      <v-legend position="top-right" :offsetY="-8" :clickable="false"/>
      <v-axis dataKey="y" :label="labelAxis" :grid="grid"/>
      <v-axis dataKey="yearMonth" :label="labelAxis" :tickLine="tickLine" :line="tickLine"/>
      <v-stack-bar position="yearMonth*y"  :color="lineColor" :label="label" :opcaity="1" :attrData="dataSource"/>
    </v-chart>
  </div>
</template>

<script>
  const DataSet = require('@antv/data-set');
  import { triggerWindowResizeEvent } from '@/utils/util'
  
  export default {
    name: 'StackBar',
    props: {
      dataSource: {
        type: Array,
        default: () => [
          { 'yearMonth': '1月', '已用预算': 25, '可用预算': 18 },
          { 'yearMonth': '2月', '已用预算': 30, '可用预算': 20 },
        ]
      },
      height: {
        type: Number,
        default: 460
      },
      padding: {
        type: Array,
        default: () => ['90', '10', '45', '45']
      }
    },
    data() {
      return {
        label: ['x', {
          useHtml: true,
          htmlTemplate: function htmlTemplate(text, item) {
            if(text === '可用预算') return '<span></span>'
            const a = item.point
            const b = a.z.find(obj=>{
              return obj.yearMonth === a.yearMonth
            })
            const c = (Number(a.y) + Number(b['可用预算'])).toFixed(2)
            return '<span style="color: #7bffe0; font-size:12px;">' + c + '</span>';
          }
        }],
        lineColor:['x',['#6d85ff', '#a0df65']],
        grid:{
          lineStyle: {
            lineWidth: 1,
            stroke: '#4658ce'
          }
        },
        tickLine: {
          stroke: '#4658ce'
        },
        labelAxis:{
          textStyle: {
            opacity: 1,
            fill: '#98baff'
          }
        },
        paddingCopy: this.padding,
      }
    },
    computed: {
      data() {
        const dv = new DataSet.View().source(this.dataSource);
        dv.transform({
          type: 'fold',
          fields: ['已用预算', '可用预算'],
          key: 'x',
          value: 'y',
          retains: ['yearMonth'],
        });
        let rows =  dv.rows
        // 替换别名
        rows.forEach(row => {
          row.z = this.dataSource
        })
        // 动态设置padding比例  
        this.resetPadding(rows)
        return rows
      }
    },
    methods: {
      resetPadding(list){
        if(!list || !list.length) return
        const arrs = list.map((value, index, array) => {
            return value.y
        })
        const maxnum = Math.max(...arrs)        
        const len = String(maxnum).length
        const n = String((len-2) * 10 )
        this.paddingCopy.splice(3,1, n)
      }
    },
    mounted () {
      triggerWindowResizeEvent()
    }
  }
</script>